package org.celery.modules.shop.service.impl;

import cn.hutool.core.io.resource.ClassPathResource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.celery.modules.shop.entity.Shop;
import org.celery.modules.shop.entity.ShopDept;
import org.celery.modules.shop.entity.ShopUser;
import org.celery.modules.shop.service.IShopDeptService;
import org.celery.modules.shop.service.IShopUserService;
import org.celery.modules.shop.vo.ShopVO;
import org.celery.modules.shop.mapper.ShopMapper;
import org.celery.modules.shop.service.IShopService;
import org.celery.modules.ticket.entity.Ticket;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.ITenantService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 店铺表 服务实现类
 *
 * @author Celery
 * @since 2023-06-12
 */
@Service
@PropertySource(value = "user.properties", encoding = "utf-8")
public class ShopServiceImpl extends BaseServiceImpl<ShopMapper, Shop> implements IShopService {

	// 用户相关信息
	@Value("${user.userPassword}")
	private String userPassword;

	@Value("${user.tenantId}")
	private String tenantId;

	@Value("${user.roleTenantId}")
	private String roleTenantId;

	@Value("${user.roleParentId}")
	private String roleParentId;

	@Value("${user.roleName}")
	private String roleName;

	@Value("${user.roleAlias}")
	private String roleAlias;

	@Value("${user.roleSort}")
	private String roleSort;

	@Value("${user.isFindRoleID}")
	private String isFindRoleID;

	@Value("${user.roleDefaultId}")
	private String roleDefaultId;

	@Override
	public IPage<ShopVO> selectShopPage(IPage<ShopVO> page, ShopVO shop) {
		return page.setRecords(baseMapper.selectShopPage(page, shop));
	}

	@Override
	public Boolean addShop(Shop shop) {
		return save(shop);
	}

	@Override
	public Boolean modifyShop(Shop shop) {
		if(Func.isEmpty(shop.getId())) {
			throw new ServiceException("请传入id");
		}
		return updateById(shop);
	}

	@Override
	public Boolean deleteShop(Long shopId) {
		return update(Wrappers.<Shop>lambdaUpdate().set(Shop::getIsDeleted, 1).eq(Shop::getId, shopId));
	}

	@Override
	public Shop getShopById(Long orderId) {
		return getOne(Wrappers.<Shop>lambdaQuery().eq(Shop::getId, orderId));
	}

	@Override
	public IPage<Shop> getShopList(Shop order, Query query) {
		return page(Condition.getPage(query), Condition.getQueryWrapper(order));
	}

	@Override
	public List<HashMap<String, String>> getShopSelect(String name, BladeUser user) {
		QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
		if (Func.isNotEmpty(name)) {
			queryWrapper.lambda().like(Shop::getResourceOwner, name);
		}
		List<Shop> shopList = list(authWrapper(queryWrapper, user));
		Map<Long, Shop> collect = shopList.stream().collect(Collectors.toMap(Shop::getId, shop -> shop));
		if(Func.isEmpty(collect)) {
			return new ArrayList<>();
		} else {
			return collect.values().stream().map(shopItem -> new HashMap<String, String>() {{
				put("label", shopItem.getResourceOwner());
				put("desc", "店铺");
				put("value", shopItem.getId().toString());
			}}).collect(Collectors.toList());
		}
	}

    @Override
    public ArrayList<String> getFileContent(String filePath) throws IOException {
		ClassPathResource classPathResource = new ClassPathResource(filePath);
		String path = classPathResource.getFile().getPath();
		// 读取需要插入的数据文件
		FileInputStream fileInputStream = new FileInputStream(path);
		InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String str = "";
		ArrayList<String> stringArr = new ArrayList<>();
		while((str = bufferedReader.readLine()) != null) {
			stringArr.add(str);
		}
		bufferedReader.close();
		return stringArr;
    }

	@Override
	public HashMap<String, String> getCustomProperties() {

		return new HashMap<String, String>() {{
			put("userPassword", userPassword);
			put("tenantId", tenantId);
			put("roleTenantId", roleTenantId);
			put("roleParentId", roleParentId);
			put("roleName", roleName);
			put("roleAlias", roleAlias);
			put("roleSort", roleSort);
			put("isFindRoleID", isFindRoleID);
			put("roleDefaultId", roleDefaultId);
		}};
	}

	@Override
	public List<Shop> authList(BladeUser user) {
		QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
		queryWrapper = authWrapper(queryWrapper, user);
		if (Func.isNull(queryWrapper)) {
			return new ArrayList<>();
		}
		return list(queryWrapper);
	}

	@Override
	public QueryWrapper<Shop> authWrapper(QueryWrapper<Shop> queryWrapper, BladeUser user) {
		if (!user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) {
			queryWrapper.lambda().eq(Shop::getTenantId, user.getTenantId());
		}
		// 如果用户角色只有运营, 仅获取关联的店铺列表
		if (user.getRoleName().equals("yunying")) {
			IShopUserService shopUserService = SpringUtil.getBean(IShopUserService.class);
			List<ShopUser> shopUserList = shopUserService.list(Wrappers.<ShopUser>lambdaQuery().eq(ShopUser::getUserId, user.getUserId()));
			if (Func.isEmpty(shopUserList)) {
				return null;
			}
			queryWrapper.lambda().in(Shop::getId, shopUserList.stream().map(ShopUser::getShopId).collect(Collectors.toList()));
			return queryWrapper;
		}

		if (user.getRoleName().contains("administrator") || user.getRoleName().contains("s_admin") || user.getRoleName().contains("caiwu") || user.getRoleName().contains("fake_boss")) {
			return queryWrapper;
		}

		IUserService userService= SpringUtil.getBean(IUserService.class);
		IDeptService deptService = SpringUtil.getBean(IDeptService.class);
		User bladeUser = userService.getById(user.getUserId());
		List<Long> deptIdList = Func.toLongList(bladeUser.getDeptId());
		if (Func.isEmpty(deptIdList)) {
			return null;
		}

		List<Dept> deptList = deptService.list(Wrappers.<Dept>lambdaQuery().in(Dept::getId, deptIdList));
		IShopDeptService shopDeptService = SpringUtil.getBean(IShopDeptService.class);
		if (Func.isEmpty(deptList)) {
			return null;
		}

		List<ShopDept> shopDeptList = shopDeptService.list(Wrappers.<ShopDept>lambdaQuery().in(ShopDept::getDeptId, deptIdList));
		if (Func.isEmpty(shopDeptList)) {
			return null;
		}
		queryWrapper.lambda().in(Shop::getId, shopDeptList.stream().map(ShopDept::getShopId).collect(Collectors.toList()));
		return queryWrapper;
	}

	@Override
	public Map<String, Object> shopUserInfo(Long shopId) {
		Map<String, Object> data = new HashMap<>();

		Shop shop = getById(shopId);
		if (Func.isEmpty(shop)) {
			return null;
		}

		ITenantService tenantService = SpringUtil.getBean(ITenantService.class);
		Tenant tenant = tenantService.getOne(Wrappers.<Tenant>lambdaQuery().eq(Tenant::getTenantId, shop.getTenantId()));
		data.put("customer", tenant.getTenantName());

		IShopDeptService shopDeptService = SpringUtil.getBean(IShopDeptService.class);
		IDeptService deptService = SpringUtil.getBean(IDeptService.class);
		List<ShopDept> shopDeptList = shopDeptService.list(Wrappers.<ShopDept>lambdaQuery().eq(ShopDept::getShopId, shopId));
		if (Func.isNotEmpty(shopDeptList)) {
			List<Dept> deptList = deptService.list(Wrappers.<Dept>lambdaQuery().in(Dept::getId, shopDeptList.stream().map(ShopDept::getDeptId).collect(Collectors.toList())));
			if (Func.isEmpty(deptList)) {
				data.put("dept", "");
			} else {
				data.put("dept", Func.join(deptList.stream().map(Dept::getDeptName).collect(Collectors.toList())));
			}
		} else {
			data.put("dept", "");
		}

		return data;
	}
}
